package com.study.common.utils;

/**
 * 进制转换工具类
 *
 * @author nizhihao
 * @version 1.0.0
 * @date 2022/1/19 19:52
 */
public class RadixUtils {

    /**
     * 字符串转16进制
     *
     * @param content 字符串
     * @return byte[]
     */
    public static byte[] hexToBytes(String content) {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        byte[] baKeyword = new byte[content.length() / 2];
        int len = baKeyword.length;
        for (int i = 0; i < len; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(content.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return baKeyword;
    }

    /**
     * byte[]转16进制字符串
     *
     * @param bytes byte[]数组
     * @return 16进制字符串
     */
    public static String bytesToHex(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

}
